package Leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class spiralOrder {

    public List<Integer> spiralOrder(int[][] matrix) {
        int lenX = matrix.length;
        int lenY = matrix[0].length;
        boolean[][] visited = new boolean[lenX][lenY];
        List<Integer> result = new ArrayList<>();
        int round = Math.min(lenX, lenY) / 2;
        int i, j;
        int startX = 0, startY = 0;
        int count = 1;
        while (round >= 0){
            i = startX;
            j = startY;
            for (; j < lenY - count; j++) {
                if (!visited[i][j]){
                    result.add(matrix[i][j]);
                    visited[i][j] = true;
                } else {
                    break;
                }
            }
            for (; i < lenX - count; i++) {
                if (!visited[i][j]){
                    result.add(matrix[i][j]);
                    visited[i][j] = true;
                } else {
                    break;
                }
            }
            for (; j > startY; j--) {
                if (!visited[i][j]){
                    result.add(matrix[i][j]);
                    visited[i][j] = true;
                } else {
                    break;
                }
            }
            for (; i > startX; i--) {
                if (!visited[i][j]){
                    result.add(matrix[i][j]);
                    visited[i][j] = true;
                } else {
                    break;
                }
            }
            startX++;
            startY++;
            count++;
            round--;
        }
        if (lenX == lenY && lenY % 2 != 0){
            result.add(matrix[lenX/2][lenY/2]);
        }
        return result;
    }
}
